package com.wl.springsecuritystudy.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * 自定义访问决策器
 * <p>
 * 1、必须有授权token
 *
 */
@Slf4j
public class RestfulVoter implements AccessDecisionVoter<Object> {

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {

        if (authentication == null) {
            return ACCESS_DENIED;
        }

        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken auth = (JwtAuthenticationToken) authentication;
            log.info("Gateway Session - userId : {} - category : {} - client : {}", auth.getSession().getUserId(), auth.getSession().getCategory(), auth.getSession().getClient());
        }

        FilterInvocation fi = (FilterInvocation) object;
        HttpServletRequest request = fi.getHttpRequest();

        log.info("Gateway Request : {} - {}", request.getMethod(), request.getRequestURI());
        return ACCESS_GRANTED;


        // for (ConfigAttribute attribute: attributes) {
        //     if (attribute instanceof RestfulConfigAttribute) {
        //         RestfulConfigAttribute ca = (RestfulConfigAttribute) attribute;
        //         if (ca.match(request)) {
        //             return ACCESS_GRANTED;
        //         }
        //     }
        // }

        // return ACCESS_ABSTAIN;
    }

    @Override
    public boolean supports(Class clazz) {
        return true;
    }
}
